package cn.ecnu.user.controller;

import cn.ecnu.common.Constant;
import cn.ecnu.user.service.UserService;
import cn.ecnu.user.util.AuthSolver;
import cn.ecnu.user.vo.PhoneCaptchaVo;
import cn.ecnu.user.vo.PhonePasswordVo;
import cn.ecnu.user.vo.RegisterWithPhoneVo;
import cn.ecnu.user.vo.UserInfoVo;
import cn.ecnu.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private AuthSolver authSolver;

    // 登录, 使用手机号和密码
    @PostMapping("/loginWithPassword")
    public R loginWithPassword(@RequestBody PhonePasswordVo vo) {
        UserInfoVo info = userService.loginWithPassword(vo);
        return R.ok().put("data", info);
    }

    // 登录, 使用手机验证码
    @PostMapping("/loginWithCaptcha")
    public R loginWithCaptcha(@RequestBody PhoneCaptchaVo vo) {
        UserInfoVo info = userService.loginWithCaptcha(vo);
        return R.ok().put("data", info);
    }

    // 注册, 使用手机号注册
    @PostMapping("/registerWithPhone")
    public R registerWithPhone(@RequestBody RegisterWithPhoneVo vo) {
        userService.registerWithPhone(vo);
        return R.ok();
    }


    // 1. 前端首先调用接口进行跳转到alipay
    @GetMapping("/authWithAlipay")
    public R login() {
        return R.ok().put("redirect", authSolver.getRedirectUrl());
    }


    // 2. alipay授权成功后跳转到前端路由, 前端提交authCode到后端
    // 3. 如果检测到用户已经注册, 就会直接分发token和具体信息
    // 4. 否则就会只返回用户的alipayId, 然后前端要求注册
    @GetMapping("/loginWithAlipay")
    public R auth(@RequestParam("auth_code") String authCode) {
        String userId = authSolver.solve(authCode);
        UserInfoVo info = userService.loginWithAlipay(userId);
        if (info.getUserId() == null) return R.error(
                Constant.NOT_BINDING.getCode(),
                Constant.NOT_BINDING.getMsg())
                .put("data", info);

        return R.ok().put("data", info);
    }
}
